<?php
namespace App\Admin\Controllers\ApiPlat\Amazon;

use Encore\Admin\Controllers\AdminController;
use App\Logic\Amazon\Api\Authorize;
use App\Models\Basics\AmazonAccount;
use GuzzleHttp\Client;
use Exception;
use Illuminate\Http\Request;
class OauthController extends AdminController{

    public function oAuth(Request $request)
    {
        $state = $request->get('state');
        $sellingPartnerId = $request->get('selling_partner_id');
        $spApiOauthCode = $request->get('spapi_oauth_code');
        if(!$state){
            return response()->json(['status' => false, 'message' => '授权状态码无效！']);
        }
        if(!$sellingPartnerId || !$spApiOauthCode){
            return response()->json(['status' => false, 'message' => '未获取到授权码！']);
        }
        $a = new Authorize();
        $cacheState = $a->parseState($state);
        $accountId = $cacheState['account_id'];
        if(!$cacheState['state'] || $state != $cacheState['state']){
            return response()->json(['status' => false, 'message' => '授权状态码失效！']);
        }
        $client = new Client();
        $response = $client->post('https://api.amazon.com/auth/o2/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'code' => $spApiOauthCode,
                'redirect_uri' => $a->getSuccessRedirectUri().'?id='.$accountId,
                'client_id' => config('spapi.lwa_client_id'),
                'client_secret' => config('spapi.lwa_client_secret'),
            ],
            'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
        ]);
        $body = $response->getBody();
        if($response->getStatusCode() == 200){
            $data = json_decode($body, true);
            $account = AmazonAccount::query()->find($accountId);
            $account->refresh_token = $data['refresh_token'];
            $account->merchant = $sellingPartnerId;
            $account->auth_status = 1;
            $account->auth_at = date('Y-m-d H:i:s');
            $flag = $account->save();
            return view('api-plat.amazon.index')->with(['message' => $flag ? '授权成功！' : '授权失败！', 'id' => $accountId]);
        }else{
            report(new Exception('['.$sellingPartnerId.']'.$body,$response->getStatusCode()));
            return view('api-plat.amazon.index')->with(['message' => '授权失败！', 'id' => $accountId]);
        }
    }

    public function oAuthorized(Request $request){
        $id = $request->get('id');
        $account = AmazonAccount::query()->find($id);
        return redirect()->action('Basics\AmazonAccountController@edit', ['amazon_account' => $account]);
    }
}
